<template>
  <div class="login-container" v-if="workbenches == 0 && workbenche1 == 0">
    <div class="login-form">
      <img class="left-img" :src="leftImg" />
      <div class="left-img1">
        <div class="font2">
          {{ 'DMS系统' }}
        </div>
        <div class="font1">
          {{ '扫码登录' }}
        </div>
        <div class="left-img2">
          <!--            <el-button class="login-btn" type="primary" @click="handleLogin">
                        {{ translateTitle('登录') }}
                      </el-button>-->
          <div id='login' />
        </div>
        <div class="font3" >
          登录视为您已同意第三方账号绑定协议、服务条款、隐私政策系统
        </div>
      </div>
    </div>
  </div>
  <div v-if="workbenches == 1">
    <figure>
      <div class="dot white"></div>
      <div class="dot"></div>
      <div class="dot"></div>
      <div class="dot"></div>
      <div class="dot"></div>
    </figure>
  </div>
  <div v-if="workbenche1 != 0">
    <figure>
      <div class="dot white"></div>
      <div class="dot"></div>
      <div class="dot"></div>
      <div class="dot"></div>
      <div class="dot"></div>
    </figure>
  </div>
</template>

<script lang="ts" setup>
import { useSettingsStore } from '/@/store/modules/settings'
import { useUserStore } from '/@/store/modules/user'
import { translateTitle } from '/@/utils/i18n'
import { isPassword } from '/@/utils/validate'
import { onBeforeRouteLeave } from 'vue-router'

import { getImageUrl } from '/@/utils/imageUrl'
import { fa } from 'element-plus/es/locale'

import router from '/@/router'
import { dmsDingLogin } from "/@/api/api";
import { ElMessage } from "element-plus";
import { gp } from "/@vab/plugins/vab";
import * as dd from "dingtalk-jsapi"
import { Ref } from "vue";
import { corpId } from "/@/config";
defineOptions({
  name: 'Login',
})

const route = useRoute()
// const router = useRouter()

const userStore = useUserStore()
const settingsStore = useSettingsStore()

const leftImg = ref('')
const img = getImageUrl(`assets/login_images/left_img.png`)
leftImg.value = img

const login = (form: any) => userStore.login(form)

const title = settingsStore.getTitle
// 判断是否在工作台登录
const workbenches: any = ref(localStorage.getItem('workbenches') || '1')
// 扫码登录 跳转判断
const workbenche1: any = ref(0)
const loading: Ref<any> = ref(false)
const redirect: Ref<any> = ref((route.query && route.query.redirect) || '/')
const timer: Ref<any> = ref(0)
const codeUrl: Ref<any> = ref('https://www.oschina.net/action/user/captcha')
const handleRoute = (list = redirect.value) => {
  return list === '/404' || list === '/403'
    ? '/'
    : list
}
const handleLogin = async () => {
  await login(form).catch(() => { })
  await router.push(handleRoute())
}
const changeCode = () => {
  codeUrl.value = `https://www.oschina.net/action/user/captcha?timestamp=${new Date().getTime()}`
}
// 正式：ding0xi7nxgkgp46jgjq
// 测试：dingdiiabokjnulteosg
const key = ref(import.meta.env.VITE_APP_BASE_KEY)
const url = ref(window.location.origin + '/redirect')
const URL = encodeURIComponent(`https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${key.value}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url.value}`)
// <***************history  获取#前面参数值   跳转页面  获取code 代码在 views/redirect/Redirect   *********************>
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
const code = ref(route.query.code);
const state = ref(params.state);
watchEffect(() => {
  if (workbenches.value == 0) {
    const url = window.location.href;
    const params: any = {};
    url.replace(/[?&]+([^=&]+)=([^&]*)/gi, (m: any, key: any, value: any) => {
      params[key] = value;
    });
    // 获取code值和state值
    code.value = params["code"];
    state.value = params["state"];
    if (code.value) {
      workbenche1.value = 1
      const history_url: any = localStorage.getItem('redirect_code')
      dmsDingLogin({ code: code.value, state: state.value }).then(async (data: any) => {
        if (data.code == 200) {
          login(data.data.token).then(() => {
            window.location.href = `${window.location.origin}/#${handleRoute(JSON.parse(history_url))}?dd=true`
          })
          await localStorage.removeItem('redirect_code')
        } else {
          window.location.href = `${window.location.origin}/#/login}`
        }
      }).catch(() => {
        ElMessage({
          message: '登录失败',
          type: 'error',
        })
      })
    }
  }
})
// <***************history  获取#前面参数值  *********************>
watchEffect(() => {
  redirect.value = (route.query && route.query.redirect) || '/'
  // DDlogin()
})
onMounted(() => {
  // localStorage.setItem('redirect_code',JSON.stringify(redirect.value))
  localStorage.setItem('redirect_code', JSON.stringify('/'))
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  // 扫码登录
  const obj = window.DDLogin({
    id: 'login',
    style: 'border: none;background-color: rgba(255,255,255,0.01) ',
    goto: URL,
    width: '100%',
    height: '300px',
  })
  // DDlogin()
})
onBeforeMount(() => {
  DDlogin()
})
const getUrlParams = (key: string) => {
  let query = window.location.search.substring(1)
  let vars = query.split("&")
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split("=")
    if (pair[0] == key) return pair[1]
  }
  return false
}
const DDlogin: any = () => {
  if (dd.env.platform !== "notInDingTalk") {
    workbenches.value = '1'
    const corpIdData: any = getUrlParams('corpId') || corpId
    dd.ready(() => {
      // 获取免登授权码
      dd.runtime.permission.requestAuthCode({
        corpId: corpIdData,
      }).then((onSuccess: any) => {
        // alert('success: '+ onSuccess.code)
        // 你的业务逻辑
        const history_url: any = localStorage.getItem('redirect_code')
        dmsDingLogin({ user_code: onSuccess.code }).then(async (data: any) => {
          if (data.code == 200) {
            await login(data.data.token).catch(() => { })
            await router.push(handleRoute(JSON.parse(history_url)))
            await localStorage.removeItem('redirect_code')
          } else {
            router.push('/login')
            // window.location.href = `${window.location.origin}/#/login}`
          }
        }).catch(() => {
          ElMessage({
            message: '登录失败',
            type: 'error',
          })
        })
      }, (onFail: any) => {
        alert('err: ' + JSON.stringify(onFail))
      })
    })
  } else {
    workbenches.value = '0'
    localStorage.setItem('workbenches', '0')
  }
}
const handleMessage = async (event: any) => {
  const origin = event.origin
  const loginTmpCode = event.data
  const URLS = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${key.value}&response_type=code&scope=snsapi_login&state=dinglogin&redirect_uri=${url.value}&loginTmpCode=${loginTmpCode}`
  if (origin == 'https://login.dingtalk.com') { //判断是否来自ddLogin扫码事件。
    //获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
    window.open(encodeURI(URLS), '_parent')
  } else {
  }
}
if (typeof window.addEventListener != 'undefined') {

  window.addEventListener('message', handleMessage, false)
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
} else { // @ts-ignore
  if (typeof window.attachEvent != 'undefined') {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    window.attachEvent('onmessage', handleMessage)

  }
}
</script>

<style lang="scss" scoped>
.login-container {
  position: relative;
  height: 100vh;
  padding-top: 20vh;
  background: url('/@/assets/login_images/background.jpg') center center fixed no-repeat;
  background-size: cover;
}

@media (max-width: 576px) {
  .login-form {
    width: 85vw !important;
    margin: auto !important;

    .left-img {
      display: none !important;
    }

    .left-img2 {
      top: 35% !important;
      left: 24% !important;
    }

    .left-img1 {
      width: 100% !important;
    }

    .font2 {
      top: -2% !important;
      left: -2% !important;
    }

    .font1 {
      top: 20% !important;
      left: -2% !important;
    }

    .font3 {
      top: 99% !important;
      left: -2% !important;
    }

    :deep() {
      .el-form--default {
        width: 94% !important;
      }
    }
  }
}

.login-form {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 1000px;
  height: 550px;
  padding: 4.5vh;
  margin: auto;
  overflow: hidden;
  background: var(--el-color-white);
  background-size: 100% 100%;
  border-radius: 15px;

  .left-img {
    float: left;
    width: 50%;
  }

  .left-img1 {
    float: left;
    width: 50%;
    height: 100%;
    position: relative;
  }

  .left-img2 {
    position: absolute;
    top: 40%;
    left: 31%;
    margin: -50px 0 0 -50px;
  }

  :deep() {
    .el-form--default {
      float: left;
      width: 44%;
      margin-left: 5.8%;
    }

    .title {
      font-size: 54px;
      font-weight: 500;
      color: var(--el-color-black);
    }

    .title-tips {
      margin-top: 29px;
      font-size: 26px;
      font-weight: 400;
      color: var(--el-color-black);
    }

    .login-btn {
      display: inherit;
      width: 100%;
      height: 50px;
      margin-top: 15px;
      border: 0;

      &:hover {
        opacity: 0.9;
      }

      .forget-passwordword {
        width: 100%;
        margin-top: 40px;
        text-align: left;

        .forget-password {
          width: 129px;
          height: 19px;
          font-size: 20px;
          font-weight: 400;
          color: rgba(92, 102, 240, 1);
        }
      }
    }

    .tips {
      margin-bottom: 10px;
      font-size: var(--el-font-size-default);
      color: var(--el-color-white);

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .title-container {
      position: relative;

      .title {
        margin: 0 auto 40px auto;
        font-size: 34px;
        font-weight: bold;
        color: var(--el-color-primary);
        text-align: center;
      }
    }

    i {
      position: absolute;
      top: 9px;
      left: 15px;
      z-index: $base-z-index;
      font-size: 16px;
      color: var(--el-color-black);
      cursor: pointer;
      user-select: none;
    }

    .show-password {
      position: absolute;
      right: 25px;
      left: -35px;
      font-size: 16px;
      color: var(--el-color-black);
      cursor: pointer;
      user-select: none;
    }

    .el-form-item {
      padding-right: 0;
      margin: 20px 0;
      color: #454545;
      background: transparent;
      border: 1px solid transparent;
      border-radius: 2px;

      &__content {
        min-height: $base-input-height;
        line-height: $base-input-height;
      }

      &__error {
        position: absolute;
        top: 100%;
        left: 18px;
        font-size: var(--el-font-size-small);
        line-height: 18px;
        color: var(--el-color-error);
      }
    }

    .el-input {
      box-sizing: border-box;

      input {
        height: 48px;
        padding-left: 35px;
        font-size: var(--el-font-size-default);
        line-height: 48px;
        background: var(--el-color-white);
        border: 0;
      }
    }

    .code {
      position: absolute;
      top: 4px;
      right: 4px;
      cursor: pointer;
      border-radius: var(--el-border-radius-base);
    }
  }

  .font1 {
    position: absolute;
    top: 22%;
    left: 2%;
    width: 100%;
    height: 50px;
    display: block;
    overflow-wrap: break-word;
    color: #000;
    font-size: 24px;
    letter-spacing: .40000001px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    text-align: center;
    white-space: nowrap;
  }

  .font2 {
    position: absolute;
    top: 0%;
    left: 2%;
    display: block;
    width: 100%;
    height: 67px;
    overflow-wrap: break-word;
    color: #636366;
    font-size: 36px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    white-space: nowrap;
    line-height: 67px;
    text-align: center;
  }

  .font3 {
    position: absolute;
    top: 103%;
    left: 6%;
    display: block;
    width: 100%;
    height: 22px;
    color: #636366;
    font-size: 5px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    text-align: center;
  }
}</style>
